package com.efeichong.common.security;

import com.efeichong.common.domain.RoleMenuVo;
import com.efeichong.common.domain.entity.redis.LoginUser;
import com.efeichong.common.domain.repository.redis.LoginUserRepository;
import com.efeichong.util.EntityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author : lxk
 * @Date : 2020/4/3
 * @Description : 权限校验
 */
@Slf4j
@Component("securityUtil")
@AllArgsConstructor
public class SecurityUtils {
    private final SecurityIgnoreConfig securityIgnoreConfig;
    private final LoginUserRepository loginUserRepository;
    private final HttpServletResponse response;

    /**
     * 检验接口是否有权限访问（必须登录）
     *
     * @param request
     * @param authentication 认证信息
     * @return
     */
    public boolean access(HttpServletRequest request, Authentication authentication) {
        if (authentication == null) {
            return false;
        }
        LoginUser loginUser;
        String socketHeader = request.getHeader("sec-websocket-protocol");
        if (EntityUtils.isNotEmpty(socketHeader)) {
            loginUser = loginUserRepository.findByToken(socketHeader);
            if (loginUser == null) {
                return false;
            }
            response.setHeader("sec-websocket-protocol", socketHeader);
        } else {
            if (EntityUtils.equals("anonymousUser", authentication.getPrincipal())) {
                return false;
            }
            //校验是否有权限访问
            loginUser = (LoginUser) authentication.getPrincipal();
        }
        //免校验
        for (String ignoreUrl : securityIgnoreConfig.getIgnoreCheck()) {
            RequestMatcher requestMatcher = new AntPathRequestMatcher(ignoreUrl);
            if (requestMatcher.matches(request)) {
                return true;
            }
        }
        List<RoleMenuVo> permissions = loginUser.getPermissions();
        for (RoleMenuVo permission : permissions) {
            if (EntityUtils.isEmpty(permission.getPerms())) {
                continue;
            }
            RequestMatcher requestMatcher = new AntPathRequestMatcher(permission.getPerms());
            if (requestMatcher.matches(request)) {
                return true;
            }
        }
        return false;
    }
}
